import 'package:dio/dio.dart';
import 'dart:convert';

class Result {
  int code;
  String message;
  dynamic data;

  bool get isFail => code != 0;

  bool get isSuccess => code == 0;

  Result({this.code = 0, this.message = "", this.data});

  factory Result.fromJson(Map<String, dynamic> json) {
    return Result(
        code: json['code'],
        message: json['message'] ?? json['msg'],
        data: json['data']);
  }

  factory Result.fromJsonResponse(Response response) {
    //print("Result fromJsonResponse: ${response.statusCode}, ${response.data}, ${response.data.runtimeType}");
    if (response.statusCode == 200) {
      if (response.data is String) {
        // 如果data是字符串，则将其转换为json
        response.data = jsonDecode(response.data);
      }
      return Result(
          code: response.data['code'],
          message: response.data['message'] ?? response.data['msg'],
          data: response.data['data']);
    } else {
      return Result(
          code: response.statusCode ?? -1,
          message: "未知错误",
          data: response.data);
    }
  }

  factory Result.fromJsonData(Map data) {
    return Result(
        code: data['code'],
        message: data['message'] ?? data['msg'],
        data: data['data']);
  }

  factory Result.fromNetworkError(String error) {
    return Result(code: -2, message: "网络错误", data: error);
  }

  @override
  String toString() {
    // TODO: implement toString
    return "code:$code ,message:$message ,data:$data";
  }
}
